package cn.com.wxd.service.attach;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.service.attach.dao.AttachDao;
import cn.com.wxd.service.attach.entity.AttachInfo;


public class AttachUtil {
    private static final Logger log = LoggerFactory.getLogger(AttachUtil.class);
    private static final String filePath = "attachconfig.xml";
    private static Document document = null;
    private static AttachUtil attachUtil;
    private static List<AttachConfEntity> attachconfs;

    public static AttachUtil instance() throws IOException, DocumentException {
        if (attachUtil == null) {
            attachUtil = new AttachUtil();
            attachUtil.init();
            return attachUtil;
        }
        if (document == null || attachconfs == null || attachconfs.size() <= 0) {
            attachUtil.init();
        }
        return attachUtil;
    }

    /**
     * 初始化附件配置文件
     * 一般在修改xml文件后执行次方法
     */
    private void init() throws IOException, DocumentException {
        try {
            SAXReader reader = new SAXReader();
            reader.setEncoding("UTF-8");
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath);
            document = reader.read(inputStream);
        } catch (DocumentException e) {
            log.error("读取附件路径配置文件错误！", e);
            throw e;
        }
        attachconfs = new ArrayList<>();

        //创建根节点
        Element root = document.getRootElement();
        //获取list节点
        List nodes = root.elements("item");
        for (Iterator it = nodes.iterator(); it.hasNext(); ) {
            Element elm = (Element) it.next();
            AttachConfEntity acf = new AttachConfEntity();
            Element ename = elm.element("name");
            Element etype = elm.element("type");
            Element epath = elm.element("path");
            Element edescription = elm.element("description");
            Element eparamname = elm.element("paramname");
            Element erecorddb = elm.element("recordDB");
            Element isbpcont = elm.element("isBpcont");
            Element isdownload = elm.element("isDownload");
            if (ename != null && ename.getTextTrim() != null) {
                acf.setName(ename.getText().trim());
            } else {
                acf.setName("");
            }
            if (etype != null && etype.getText() != null && !etype.getText().trim().isEmpty()) {
                acf.setType(etype.getText().trim());
            } else {
                acf.setType("");
            }
            if (epath != null && epath.getText() != null && !epath.getText().trim().isEmpty()) {
                acf.setPath(epath.getText().trim());
            } else {
                throw new DocumentException("attachconfig.xml文件，path节点没有配置，或不能为空！");
            }
            if (edescription != null && edescription.getText() != null) {
                acf.setDescription(edescription.getText());
            } else {
                acf.setDescription("");
            }
            if (isbpcont != null && isbpcont.getText() != null) {
                acf.setIsBpcont(isbpcont.getText().trim());
            } else {
                acf.setIsBpcont("false");
            }
            if (isdownload != null && isdownload.getText() != null) {
                acf.setIsDownload(isdownload.getText().trim());
            } else {
                acf.setIsDownload("false");
            }
            if (eparamname != null && eparamname.getText() != null && !eparamname.getText().trim().isEmpty()) {
                acf.setParamname(eparamname.getText());
            } else {
                throw new DocumentException("attachconfig.xml文件，paramname节点没有配置，或不能为空！");
            }
            if (erecorddb != null && erecorddb.getText() != null) {
                acf.setRecorddb(erecorddb.getText().trim());
            } else {
                acf.setRecorddb("true");
            }
            attachconfs.add(acf);
        }
        if (!validatAttachEntitys()) {
            throw new DocumentException("attachconfig.xml文件，paramname不能重复！");
        }
    }

    /**
     * 获取所有的配置文件信息
     *
     * @return
     */
    public List<AttachConfEntity> getAttachConfEntitys() {
        return attachconfs;
    }

    /**
     * 根据配置的paramName信息获取该配置文件信息
     *
     * @return
     */
    public AttachConfEntity getAttachConfByParamName(String paramName) {
        AttachConfEntity ace = null;
        for (int i = 0; i < attachconfs.size(); i++) {
            if (attachconfs.get(i).getParamname().equalsIgnoreCase(paramName)) {
                ace = attachconfs.get(i);
                break;
            }
        }
        return ace;
    }

    /**
     * 根据文件上传后的名称获取存入数据库的文件的信息
     *
     * @param upFileName
     *
     * @return
     */
    public AttachInfo getAttachInfoByDBupfileName(String upFileName) {
        if (upFileName == null || upFileName.trim().equals("")) {
            return null;
        }
        AttachDao attachDao = new AttachDao();
        return attachDao.getAttachInfoByFileName(upFileName);
    }

    /**
     * 根据上传文件后保存到数据库的文件信息id获取文件信息
     *
     * @param id
     *
     * @return
     */
    public AttachInfo getAttachInfoBuDBFileId(String id) {
        if (id == null || id.trim().equals("")) {
            return null;
        }
        AttachDao attachDao = new AttachDao();
        return attachDao.getAttachInfoById(id);
    }

    /**
     * 校验配置文件数据的正确性
     *
     *
     * @return true可用，false不可用
     */
    private boolean validatAttachEntitys() {
        if (attachconfs == null || attachconfs.size() <= 0) {
            return false;
        }
        for (int i = 0; i < attachconfs.size(); i++) { //判断是否有重复的paranName
            for (int j = i; j < attachconfs.size(); j++) {
                if (j == i) {
                    continue;
                }
                if (attachconfs.get(i).getParamname().equalsIgnoreCase(attachconfs.get(j)
                        .getParamname())) {
                    return false;
                }
            }
        }
        return true;
    }
}
